<template>
  <div class="bei" style="height: 98vh;width: 101%;">
    <div
      style="margin-left: 8px; padding-top: 10px;  background-color: aqua;opacity:0.9;width: 200px;height:55px;border-radius: 50px;">
      <p style="margin-left: 25px; font-family:'Courier New', Courier, monospace; color:salmon;font-size: 20px;">{{
        room.roomName }}
        <i @click="exit" style="margin-left: 78px;" class="el-icon-switch-button"></i>
      </p>
      <p style="margin-left: 20px; font-family: 'Courier New', Courier, monospace; color:salmon;font-size: 13px;">
        房间ID:{{ room.rid }} </p>
    </div>
    <div style="display: flex;">
      <liaoUhotoVue />
      <div style="width: 540px;height: 550px;margin-top: -10px;">
        <div class="overflow" style="width: 540px;height: 550px;background-color: #f2f7fb;opacity: 0.9;overflow-x: hidden;overflow-y: auto;padding: 5px;">
          <div v-for="item in messageList" :key="item.time">
            <div v-if="item.userID !== myUser[0].uid && item.UploadFile === null && item.msgSVG === null"
              style="width: 100%;height: auto;display: flex;margin-top: 10px;margin-bottom: 10px;">
              <img :src="item.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
              <div
                style="min-width: 60px;max-width: 350px; width: auto;height: auto;padding: 5px;margin-left: 2px; background-color: #fff;border-radius: 10px;">
                {{ item.message }}
              </div>
            </div>
            <div v-if="item.userID === myUser[0].uid && item.UploadFile === null && item.msgSVG === null"
              style="width: 100%;height: auto;display: flex;flex-direction: row-reverse;margin-top: 10px;margin-bottom: 10px;">
              <img :src="item.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
              <div
                style="min-width: 60px;max-width: 350px;width: auto;height: auto;padding: 5px; background-color: chartreuse;border-radius: 10px;">
                {{ item.message }}
              </div>
            </div>
            <div v-if="item.userID === myUser[0].uid && item.UploadFile != null && item.msgSVG == null"
              style="width: 100%;height: auto;display: flex;flex-direction: row-reverse;margin-top: 10px;margin-bottom: 10px;">
              <img :src="item.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
              <div
                style="min-width: 150px;width: auto;height: auto; padding: 5px;background-color: chartreuse;border-radius: 10px;">
                <el-image :src="item.UploadFile" style="width: 150px;height: 120px;"
                  :preview-src-list="[item.UploadFile]"></el-image>
              </div>
            </div>
            <div v-if="item.userID !== myUser[0].uid && item.UploadFile != null && item.msgSVG == null"
              style="width: 100%;height: auto;display: flex;margin-top: 10px;margin-bottom: 10px;">
              <img :src="item.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
              <div
                style="min-width: 150px;width: auto;height: auto;padding: 5px; background-color: #fff;border-radius: 10px;">
                <el-image :src="item.UploadFile" style="width: 150px;height: 120px;"
                  :preview-src-list="[item.UploadFile]"></el-image>
              </div>
            </div>
            <div v-if="item.userID === myUser[0].uid && item.msgSVG != null && item.UploadFile == null"
              style="width: 100%;height: auto;display: flex;flex-direction: row-reverse;margin-top: 10px;margin-bottom: 10px;">
              <img :src="item.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
              <div
                style="min-width: 150px;max-width: 350px;width: auto;height: auto; padding: 5px;background-color: chartreuse;border-radius: 10px;">
                <video ref="video" controls controlslist="nodownload" autoplay preload="none" width="250" height="200"
                  :src="item.msgSVG">
                </video>
              </div>
            </div>
            <div v-if="item.userID !== myUser[0].uid && item.msgSVG != null && item.UploadFile == null"
              style="width: 100%;height: auto;display: flex;margin-top: 10px;margin-bottom: 10px;">
              <img :src="item.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
              <div
                style="min-width: 150px;max-width: 350px;width: auto;height: auto;padding: 5px; background-color: #fff;border-radius: 10px;">
                <video ref="video" controls controlslist="nodownload" autoplay preload="none" width="250" height="200"
                  :src="item.msgSVG">
                </video>
              </div>
            </div>
          </div>
        </div>
        <div style="background-color: #f8fafb;height: 50px;width: 550px;">
          <el-button :loading="sengIMG" type="primary"
            style="margin: 0 10px 0 0; padding: 0;height: 40px;text-align: center;line-height: 40px;font-size: 16px;"><label
              for="ImgFile">
              <p style="width: 117px;height: 40px;line-height: 40px;"><span v-if="!sengIMG">分享图片<i
                    class="el-icon-upload el-icon--right"></i></span></p>
            </label></el-button>
          <input type="file" id="ImgFile" v-show="false" @change="chooseFile" />
          <el-button :loading="sengSVG" type="primary"
            style="margin: 0; padding: 0;height: 40px;text-align: center;line-height: 40px;font-size: 16px;"><label
              for="fileVideo">
              <p style="width: 117px;height: 40px;line-height: 40px;"><span v-if="!sengSVG">分享视频<i
                    class="el-icon-upload el-icon--right"></i></span></p>
            </label>
          </el-button>
          <input type="file" id="fileVideo" v-show="false" @change="showVideo" />
          <div class="input">
            <el-input type="textarea" :rows="2" style="width:470px;font-size: 16px;" placeholder="请输入内容" v-model="chat">
            </el-input>
            <el-button type="primary" style="height: 60px;width: 80px;margin-top: -30px;font-size: 19px;"
              @click="roomMessageButton()">发送</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import liaoUhotoVue from '@/components/liaoUhoto.vue'
import EventBus from '@/util/EventBus'
export default {
  data () {
    return {
      myUser: [JSON.parse(sessionStorage.getItem('user'))],
      room: JSON.parse(this.$route.query.room),
      chat: '',
      messageList: [],
      roomUsers: [],
      msgIMG: null,
      msgType: '1',
      imgType: 'jpg',
      UploadFile: null,
      msgSVG: null,
      SVGType: 'mp4',
      SVGFile: null,
      sengIMG: false,
      sengSVG: false
    }
  },
  components: {
    liaoUhotoVue
  },
  methods: {
    CreateRoomSeng () {
      if (this.myUser[0].uid != null) {
        const webSocketUrl = 'ws://152.136.143.223:9091/webSocketRoomMessage/' + this.room.rid + '/' + this.myUser[0].uname + '/' + this.myUser[0].uid
        this.webSocketObject = new WebSocket(webSocketUrl)
        this.webSocketObject.onopen = this.webSocketOnOpen
        this.webSocketObject.onmessage = this.webSocketOnMessage
        this.webSocketObject.onerror = this.webSocketOnError
        this.webSocketObject.onclose = this.webSocketOnClose
      }
    },
    webSocketOnOpen (e) {
      console.log('与服务端连接打开->', e)
    },
    webSocketOnMessage (e) {
      console.log('->', e)
      const receiveMessage = JSON.parse(e.data)
      this.messageList.push(receiveMessage)
    },
    webSocketOnError (e) {
      console.log('与服务端连接异常->', e)
    },
    webSocketOnClose (e) {
      console.log('与服务端连接关闭->', e)
    },
    roomMessageButton () {
      const userID = this.myUser[0].uid
      const message = this.chat
      const username = this.myUser[0].uname
      const uphoto = this.myUser[0].uphoto
      const UploadFile = this.UploadFile
      const msgSVG = this.msgSVG
      if (UploadFile != null) {
        this.msgType = '2'
      } else if (msgSVG != null) {
        this.msgType = '3'
      }
      const type = this.msgType

      this.chat = ''
      this.msgType = '1'
      this.UploadFile = null
      this.msgSVG = null
      this.webSocketObject.send(JSON.stringify({
        userID,
        username,
        message,
        uphoto,
        type,
        UploadFile,
        msgSVG,
        time: new Date().getTime()
      }))
      if (UploadFile === null && msgSVG === null) {
        axios.defaults.withCredentials = true
        axios({
          url: 'http://152.136.143.223:9091/room/insertChat',
          method: 'POST',
          data: ({
            chitchatIn: this.myUser[0].uid,
            messageText: this.chat
          })
        }).then((res) => {
          if (res.data.data > 0) {
            this.chat = ''
          }
        })
      }
      // {
      //   userID,
      //   username,
      //   message,
      //   uphoto,
      //   type,
      //   msg,
      //   time: new Date().getTime()
      // }
    },
    exit () {
      const roomUID = this.room.accroom.roomInitiator
      const uid = this.myUser[0].uid
      const length = this.roomUsers.length

      if (roomUID === uid && length > 1) {
        this.$notify({
          title: '警告',
          message: '你当前是房主，此操作会关闭当前房间且需要所有房间成员退出',
          type: 'warning'
        })
      } else if (roomUID === uid && length === 1) {
        axios.defaults.withCredentials = true
        axios({
          url: 'http://152.136.143.223:9091/room/deleteRoom/' + this.room.rid + '/' + this.myUser[0].uid,
          method: 'put'
        }).then((res) => {
          if (res.data.data > 0) {
            this.$router.push({
              path: '/rooms'
            })
            this.webSocketObject.close()
            this.$notify({
              title: '成功',
              message: '房间删除成功',
              type: 'success'
            })
          }
        })
      } else if (uid !== roomUID) {
        this.roomUsers = this.roomUsers.filter(element => {
          return this.myUser[0].uid !== element.uid
        })
        EventBus.$emit('setRoomUsers', this.RoomUsers)
        axios.defaults.withCredentials = true
        axios({
          url: 'http://152.136.143.223:9091/room/exitRoom/' + this.room.rid + '/' + this.myUser[0].uid,
          method: 'get'
        }).then((res) => {
          this.$router.push({
            path: '/rooms'
          })
          this.webSocketObject.close()
          this.$notify({
            title: '成功',
            message: '退出房间成功',
            type: 'success'
          })
        })
      }
    },
    // 将本地图片转化为Base64
    chooseFile () {
      const files = document.getElementById('ImgFile').files[0]
      this.imgType = files.name.substring(files.name.lastIndexOf('.') + 1)
      const reader = new FileReader()
      reader.readAsDataURL(files)
      reader.onload = () => {
        // console.log('file 转 base64结果：' + reader.result)
        this.msgIMG = reader.result
      }
      reader.onerror = function (error) {
        console.log('Error: ', error)
      }
    },
    RoomMsgIMG () {
      this.sengIMG = true
      this.$message({
        showClose: true,
        message: '请等待，图片正在发送'
      })
      const data = {
        uphoto: this.msgIMG.replace(/^data:image\/\w+;base64,/, '')
      }
      const Type = this.imgType
      axios.defaults.withCredentials = true
      axios({
        url: 'http://152.136.143.223:9091/room/sengIMGANDSVG/' + Type,
        method: 'POST',
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        withCredentials: true,
        data: (data)
      }).then((response) => {
        this.sengIMG = false
        this.UploadFile = response.data
      })
    },
    //  上传视频
    showVideo () {
      const files = document.getElementById('fileVideo').files[0]
      this.SVGType = files.name.substring(files.name.lastIndexOf('.') + 1)
      const reader = new FileReader()
      reader.readAsDataURL(files)
      reader.onload = () => {
        // console.log('file 转 base64结果：' + reader.result)
        this.SVGFile = reader.result
      }
      reader.onerror = function (error) {
        console.log('Error: ', error)
      }
    }
  },
  mounted () {
    EventBus.$on('getUsers', (roomUsers) => {
      this.roomUsers = roomUsers
    })
  },
  beforeMount () {
    this.CreateRoomSeng()
  },
  watch: {
    msgIMG () {
      this.RoomMsgIMG()
    },
    UploadFile () {
      if (this.UploadFile != null) {
        this.roomMessageButton()
      }
    },
    SVGFile () {
      this.sengSVG = true
      this.$message({
        showClose: true,
        message: '请等待，视频正在发送'
      })
      if (this.SVGFile != null) {
        const data = {
          uphoto: this.SVGFile.replace(/^data:video\/\w+;base64,/, '')
        }
        const Type = this.SVGType
        axios.defaults.withCredentials = true

        axios({
          url: 'http://152.136.143.223:9091/room/sengIMGANDSVG/' + Type,
          method: 'POST',
          headers: { 'Content-Type': 'application/json;charset=UTF-8' },
          withCredentials: true,
          data: (data)
        }).then((response) => {
          this.sengSVG = false
          this.msgSVG = response.data
        })
      }
    },
    msgSVG () {
      if (this.msgSVG !== null) {
        this.roomMessageButton()
      }
    },
    messageList () {
      const div = document.getElementsByClassName('overflow')[0]
      setTimeout(() => {
        div.scrollTop = div.scrollHeight
      }, 0.1)
    }
  }
}
</script>

<style scoped lang="scss">
.el-avatar {
  margin: 20px;
  width: 100px;
  height: 100px;
  background: #B2C1F1;
  opacity: 0.8;
}

.el-icon-microphone {
  margin: 30px;
}

.bei {
  background-image: url(https://www.bing.com/th/id/OGC.25c774d83c40e63025efaa96bb01640d?pid=1.7&rurl=http%3a%2f%2fimg.mp.itc.cn%2fupload%2f20170520%2f1707ab3d301a49a68770ab9ecdbbca89_th.jpg&ehk=h4RrWSMgwF9FZGKxB31A6gYvwDDHjsP36ccbg8gcpA0%3d
);
  background-size: cover;
  /* 可选，控制背景图片的大小 */
  background-repeat: no-repeat;
  /* 可选，控制背景图片的重复方式 */
}
</style>
